package edu.fudan.lwang.worker;

import org.opencv.core.Mat;
import org.opencv.highgui.VideoCapture;

import edu.fudan.lwang.CodecHelper;
import edu.fudan.lwang.Common.CodecType;
import edu.fudan.lwang.callback.EncoderCallback;

public class EncoderWorker extends Thread {

	private String encoderId;
	private CodecType codecType;
	private EncoderCallback mEncoderCallBack;
	public int frameWidth;
	public int frameHeight;
	private VideoCapture capture;
	
	public EncoderWorker(String encoderId, CodecType codecType, EncoderCallback mEncoderCallBack,
						int frameWidth, int frameHeight, VideoCapture capture) {
		this.encoderId = encoderId;
		this.codecType = codecType;
		this.mEncoderCallBack = mEncoderCallBack;
		this.frameWidth = frameWidth;
		this.frameHeight = frameHeight;
		this.capture = capture;
	}
	
	public int registerEncoder() {
		int codecTypeInt = CodecHelper.getInstance().getCodecTypeInt(codecType);
		return CodecHelper.getInstance().registerEncoder(encoderId, codecTypeInt, frameWidth, frameHeight);
	}
	
	public void releaseEncoder() {
		CodecHelper.getInstance().releaseEncoder(encoderId);
	}
	
	@Override
	public void run() {
		
		Mat frame = new Mat();
		while(!Thread.interrupted() && capture.read(frame)) {
			Mat processedMat = mEncoderCallBack.beforeDataEncoded(frame);
			byte[] encodedData = CodecHelper.getInstance().encodeFrame(encoderId, processedMat.nativeObj);
			mEncoderCallBack.onDataEncoded(encodedData);
		}
		releaseEncoder();
		/**
		 * send msg to stop decoder
		 */
	}
}
